package xyz.xiaoshengfu.xrpc.provider;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import xyz.xiaoshengfu.xrpc.common.MarshallingCodeCFactory;
import xyz.xiaoshengfu.xrpc.data.XRpcResources;

/**
 * <p>Title: XRpcProviderServer</p>
 * <p>Description: xRPC服务提供者服务端</p>
 * @author xiaoshengfu(2439323118@qq.com)
 * @date 2020年2月25日
 */
public final class XRpcProviderServer {

	public XRpcProviderServer() {
		super();
	}

	public void run() {
		NioEventLoopGroup bossGroup = new NioEventLoopGroup(2);
		NioEventLoopGroup workGroup = new NioEventLoopGroup(4);
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
					.childHandler(new ChannelInitializer<SocketChannel>() {
						protected void initChannel(SocketChannel socketChannel) throws Exception {
							ChannelPipeline p = socketChannel.pipeline();
							p.addLast(new IdleStateHandler(5, 5, 5));
							p.addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
							p.addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
							p.addLast(new XRpcProviderServerHandler());
						}
					});

			Channel ch = bootstrap.bind(XRpcResources.xRpcConfig.getProtocolConfig().getPort()).sync().channel();
			ch.closeFuture().sync();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			bossGroup.shutdownGracefully();
			workGroup.shutdownGracefully();
		}
	}
}